<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2021 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2021/5/8 10:45
// +----------------------------------------------------------------------
declare(strict_types=1);

namespace buwang\util\bytedance;

use app\common\model\MemberMiniapp;
use app\common\model\MemberPayment;

class Ttlib
{
    public $payment_salt = '';
    public $mp_toutiao_appid = '';
    public $mp_toutiao_secret = '';
    public $mp_token = '';
    protected $valid_time = 30*60;


    public function __construct($member_miniapp_id=0){
        if($member_miniapp_id)$this->setConfig(['bw_member_app_id'=>$member_miniapp_id]);//设置头条配置
    }


    /**
    * @param $code
    * @return array
    */
    public function code_to_token($code)
    {
        $result = [
            'status' => false,
            'data' => [],
            'msg' => ''
        ];

//        $config = getAddonsConfig('MPToutiao');
//        if (!$config) {
//            $result['msg'] = '请开启头条小程序插件';
//            return $result;
//        }
//        $config['mp_toutiao_appid'] = 'ttcd34bb89520c4bf401';
//        $config['mp_toutiao_secret'] = '9809ba4766e2970b60ee6fca827f3b6229095afe';
        $url = 'https://developer.toutiao.com/api/apps/jscode2session?appid=' . $this->mp_toutiao_appid . '&secret=' . $this->mp_toutiao_secret . '&code=' . $code;

        $client = new \http\Request();
        $res = $client->get($url)->array();

        if ($res['error'] == 0) {
            $result['data'] = $res;
            $result['status'] = true;
        } else {
            $result['msg'] = $res['errcode'] . ':' . $res['errmsg'];
        }

        return $result;
    }


    /**
     * 获取AccessToken
     * @param string $grant_type
     * @return array
     */
    public function getAccessToken($grant_type = 'client_credential')
    {
        $result = [
            'status' => false,
            'data' => [],
            'msg' => ''
        ];

        $config = getAddonsConfig('MPToutiao');
        if (!$config) {
            $result['msg'] = '请开启头条小程序插件';
            return $result;
        }

        $key = $config['mp_toutiao_appid'] . '_' . $config['mp_toutiao_secret'];
        $val = Cache::get($key);
        if (!$val) {
            $url = 'https://developer.toutiao.com/api/apps/token?appid=' . $config['mp_toutiao_appid'] . '&secret=' . $config['mp_toutiao_secret'] . '&grant_type=' . $grant_type;

            $curl = new Curl();
            $res = $curl->get($url);
            $res = json_decode($res, true);

            if ($res['error'] == 0) {
                $result['data'] = $res['access_token'];
                Cache::set($key, $res['access_token'], 3600);
                $result['status'] = true;
            } else {
                $result['msg'] = $res['errcode'] . ':' . $res['errmsg'];
            }
        } else {
            $result['status'] = true;
            $result['data'] = $val;
        }

        return $result;
    }

    /**得到租户头条配置
     * @param $member_miniapp_id
     */
    public function setConfig($data){
        if(!isset($data['bw_member_app_id'])) throw new \Exception('缺少租户应用id参数bw_member_app_id');
        $config = MemberPayment::getPayConfig((int)$data['bw_member_app_id'], 'tt_wechat');//apiname为 wechat alipay
        if (empty($config) || !$config || !isset($config['mp_toutiao_token'])||!isset($config['mp_toutiao_salt'])) throw new \Exception('请确认头条支付配置是否有问题');
        $this->mp_token = $config['mp_toutiao_token'];
        $this->payment_salt = $config['mp_toutiao_salt'];
        //得到appid 和 appsecrat
        $memberMiniapp = MemberMiniapp::where('id',$data['bw_member_app_id'])->find();
        if(!$memberMiniapp) throw new \Exception('未找到购买的应用');
        $this->mp_toutiao_appid = $memberMiniapp['tt_appid'];
        $this->mp_toutiao_secret = $memberMiniapp['tt_secret'];
        return $this;
    }


    /**
     * 二维码生成
     * @param $access_token
     * @param $tt_platform
     * @param $page
     * @param $parameter
     * @param $width
     * @param $set_icon
     * @return array
     */
    public function getParameterQRCode($access_token, $tt_platform, $page, $parameter, $width, $set_icon)
    {
        $result = [
            'status' => false,
            'data' => [],
            'msg' => ''
        ];

        $config = getAddonsConfig('MPToutiao');
        if (!$config) {
            $result['msg'] = '请开启头条小程序插件';
            return $result;
        }

        $filename = "static/qrcode/toutiao/" . md5($config['mp_toutiao_appid'] . '_' . $config['mp_toutiao_secret'] . '_' . $tt_platform . '_' . $page . '_' . $parameter . '_' . $width . '_' . $set_icon) . '.jpg';

        if (file_exists($filename)) {
            //有这个二维码了
            $return['status'] = true;
            $return['msg'] = '二维码获取成功';
            $return['data'] = $filename;
        } else {
            $url = 'https://developer.toutiao.com/api/apps/qrcode';
            $data = [
                'access_token' => $access_token,
                'appname' => $tt_platform,
                'path' => $page.'%3f'.'scene%3d'.$parameter,
                'width' => $width,
                'set_icon' => $set_icon,
            ];

            $curl = new Curl();
            $res = $curl->post($url, $data);
            $flag = json_decode($res, true);

            if ($flag && $flag['errcode'] == -1) {
                $return['msg'] = '后台生成小程序二维码出现系统错误';
                return $return;
            } else if ($flag && $flag['errcode'] == 40002) {
                $return['msg'] = '后台生成小程序二维码access_token错误';
                return $return;
            } else if ($flag && $flag['errcode'] == 40016) {
                $return['msg'] = '后台生成小程序二维码appname错误';
                return $return;
            } else if ($flag && $flag['errcode'] == 40021) {
                $return['msg'] = '后台生成小程序二维码宽度超过指定范围';
                return $return;
            } else if ($flag && $flag['errcode'] == 60003) {
                $return['msg'] = '后台生成小程序二维码频率超过限制';
                return $return;
            } else {
                $return['msg'] = '后台生成小程序二维码参数错误：'.$flag['errcode'].'：'.$flag['errmsg'];
                return $return;
            }

            $file = fopen($filename, "w");//打开文件准备写入
            fwrite($file, $res);//写入
            fclose($file);//关闭

            if (file_exists($filename)) {
                $return['status'] = true;
                $return['msg'] = '二维码获取成功';
                $return['data'] = $filename;
            }
        }

        return $result;
    }

    /**
     * 头条支付下单接口
     * @param array $data
     */
    public function bwUnifiedOrder(array $data){
        try{
        $this->setConfig($data);//设置头条配置
        $result = [
            'status' => false,
            'data' => [],
            'msg' => ''
        ];
        if(isset($data["bw_member_app_id"])) unset($data["bw_member_app_id"]);
        $data = array_merge($data,[
            'app_id' => $this->mp_toutiao_appid,
            'valid_time' =>$this->valid_time,
        ]);
        $data['sign'] = $this->getSign($data);
//        $result['data'] = $data;
//        $result['status'] = true;

        $url = 'https://developer.toutiao.com/api/apps/ecpay/v1/create_order';

        $client = new \http\Request();
        $res = $client->asJson()->post($url,$data)->array();

        if ($res['err_no'] == 0) {
            $result['data'] = $res;
            $result['status'] = true;
        } else {
            $result['msg'] = $res['err_no'] . ':' . $res['err_tips'];
        }
        return $result;

        }catch (\Exception $e){
            return  [
                'status' => false,
                'data' => [],
                'msg' => $e->getMessage()
            ];
        }
    }
    /**
     * 头条系请求计算签名
     * @param $params
     * @return string
     */
    public function getSign($params)
    {
        unset($params["bw_member_app_id"]);
        unset($params["sign"]);
        unset($params["app_id"]);
        unset($params["thirdparty_id"]);
        $paramArray = [];
        foreach ($params as $param) {
            $paramArray[] = trim((string)$param);
        }
        $paramArray[] = trim($this->payment_salt);
        sort($paramArray,2);
        $signStr = trim(implode('&', $paramArray));
        return md5($signStr);
    }
    /**
     * 头条系支付回调解签
     * @param $params
     * @return string
     */
    public function verifySign($params)
    {
        unset($params["msg_signature"]);
        unset($params["type"]);
        $paramArray = [];
        foreach ($params as $param) {
            $paramArray[] = trim((string)$param);
        }
        sort($paramArray,2);
        $signStr = trim(implode('', $paramArray));
        return sha1($signStr);
    }
}